import logging
import os

import motor
import tornado
import tornado.web

from api_auth import APILoginHandler, APILogoutHandler, APIRegisterHandler
from api_class import (APIClassAdminHandler, APIClassDetailHandler,
                       APIClassHandler, APIMyClassHandler)
from api_container import (WebSocketContainerFileHandler,
                           WebSocketTerminalHandler)
from api_lab import APILabAdminHandler, APILabDetailHandler
from api_image import APIImageHandler
from api_massage import APIMassageHandler
from api_discuss import APIDiscussHandler
from api_user import APIMyHandler
from config import cookie_secret, db_uri

db_client = motor.motor_tornado.MotorClient(db_uri)
logging.basicConfig(level=logging.DEBUG)

base_dir = os.path.dirname(__file__)
settings = {
    'cookie_secret': cookie_secret,
    'debug': True,
    'autoreload': True,
    'db': db_client.ns3web,
}
handlers = [
    # 登录
    tornado.web.url(r'/login', APILoginHandler),
    # 登出
    tornado.web.url(r'/logout', APILogoutHandler),
    # 注册，判断用户存在
    tornado.web.url(r'/register', APIRegisterHandler),
    # 课堂列表，查询课堂
    tornado.web.url(r'/class', APIClassHandler),
    # 课堂详情，加入退出课堂
    tornado.web.url(r'/class/[a-z0-9]{24}', APIClassDetailHandler),
    # 创建课堂，管理课堂
    tornado.web.url(r'/class/admin', APIClassAdminHandler),
    # 我的课堂
    tornado.web.url(r'/class/my', APIMyClassHandler),
    # 我的信息，修改我的信息
    tornado.web.url(r'/my', APIMyHandler),
    # 课程详情，获取开始暂停结束实验
    tornado.web.url(r'/lab/[a-z0-9]{24}', APILabDetailHandler),
    # 获取学生实验情况
    tornado.web.url(r'/lab/admin/[a-z0-9]{24}', APILabAdminHandler),
    # 镜像获取，添加删除镜像
    tornado.web.url(r'/image', APIImageHandler),
    # 消息列表，消息操作
    tornado.web.url(r'/massage', APIMassageHandler),
    # 发表讨论，讨论列表
    tornado.web.url(r'/discuss/[a-z0-9]{24}', APIDiscussHandler),
    tornado.web.url(r'/file/[a-z0-9]{64}', WebSocketContainerFileHandler),
    tornado.web.url(r'/terminal/[a-z0-9]{64}', WebSocketTerminalHandler),

]
app = tornado.web.Application(handlers, **settings)
server = tornado.httpserver.HTTPServer(app)
server.listen(8080)
tornado.ioloop.IOLoop.current().start()
